package com.ptl.bp.controller;


import com.ptl.bp.config.ApiResult;
import com.ptl.bp.config.GlobalUserContext;
import com.ptl.bp.entity.TokenInfoEntity;
import com.ptl.bp.entity.UserEntity;
import com.ptl.bp.dto.TokenRefreshRequest;
import com.ptl.bp.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Tag(name = "认证管理")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @Operation(summary = "登录")
    @PostMapping("/login")
    public ApiResult<TokenInfoEntity> login(@RequestBody UserEntity entity) {
        TokenInfoEntity tokenInfoEntity = authService.login(entity);
        return ApiResult.success(tokenInfoEntity);
    }

    @Operation(summary = "刷新访问令牌")
    @PostMapping("/refresh")
    public ApiResult<TokenInfoEntity> refreshToken(@Valid @RequestBody TokenRefreshRequest request) {
        TokenInfoEntity tokenInfoEntity = authService.refreshToken(request);
        return ApiResult.success(tokenInfoEntity);
    }

    @Operation(summary = "刷新访问令牌")
    @PostMapping("/logout")
    public ApiResult<Void> logout() {
        if (GlobalUserContext.getUser() != null) {
            return ApiResult.success(null);
        }
        authService.lambdaUpdate().eq(TokenInfoEntity::getAccessToken, GlobalUserContext.getUser().getAccessToken()).remove();
        return ApiResult.success(null);
    }
}